const express = require('express')
const app = express()
const response = require('./pool/Response')
const uuid = require('uuid')
//配置跨域
const cors = require('cors')
app.use(cors({
    origin:'*'
}))
app.listen(9000,() => {
    console.log('上传文件服务已经启动')
})

//配置multer中间件。处理文件上传
const multer = require('multer')
const uplodTools = multer({
    storage:multer.diskStorage({  //该存储方法会将文件存入磁盘
        destination:(req,file,callback) => {
            callback(null,'static')   //存入名为static文件夹中
        },
        filename:(req,file,callback) => {
            //通过file，获取原文件名
            let name = file.originalname
            //截取源文件的后缀
            let ext = name.substr(name.lastIndexOf('.'))
            //生成一个随机文件名，调用callback返回
            let newName = uuid.v4() + ext
             callback(null,newName)
        }
    })
})


//配置静态资源文件
app.use(express.static('static'))

app.post('/upload',uplodTools.single('file'),(req,res) => {
    //uploadTools方法会将file字段文件接受并保存
    let url = 'http://localhost:9000/' + req.file.filename
    res.send(response.ok(url))
})
